package com.nercel.dsj.gksales.api.controller;

import com.nercel.dsj.gksales.constant.Const;
import com.nercel.dsj.gksales.exception.ResponseCode;
import com.nercel.dsj.gksales.exception.RestApiException;
import com.nercel.dsj.gksales.model.ResponseResult;
import com.nercel.dsj.gksales.model.dto.LoginParamsDTO;
import com.nercel.dsj.gksales.model.dto.UserInfoResultDTO;
import com.nercel.dsj.gksales.model.entity.Role;
import com.nercel.dsj.gksales.model.entity.User;
import com.nercel.dsj.gksales.service.RoleService;
import com.nercel.dsj.gksales.service.SalesChannelService;
import com.nercel.dsj.gksales.service.UserService;
import com.nercel.dsj.gksales.shiro.util.JwtUtils;
import com.nercel.dsj.gksales.util.ApiResultUtil;
import com.nercel.dsj.gksales.util.JwtUtil;
import com.nercel.dsj.gksales.util.Md5Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author sunlin
 * @date 2018-11-19
 */
@RestController
@Api(tags = "常规通用接口")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CommonApiController {

    private final UserService userService;

    private final RoleService roleService;

    private final static Integer AGENT_ROLE_ID = 64;


	@PostMapping(value = "/api/v1/login")
    @ApiOperation(value = "登录")
    public Object login(@ApiParam(value = "登录信息") @RequestBody LoginParamsDTO loginData) {
		if(loginData.getUsername() == null || loginData.getUsername().trim().equals("")){
			throw new RestApiException(ResponseCode.INVALID_USERNAME_OR_PASSWORD);
		}
		User user = userService.findByPhone(loginData.getUsername());
		if(user == null
				|| !user.getPassword().equals(Md5Util.getMD5String(user.getSalt() + loginData.getPassword()))) {
			throw new RestApiException(ResponseCode.INVALID_USERNAME_OR_PASSWORD);
		}
		List<Role> roles = roleService.selectByUserIdWithPermissions(user.getId());
		if(roles.size() == 0){
			List<Integer> defIds = new ArrayList<>();
			defIds.add(AGENT_ROLE_ID);
			userService.updateRoles(user.getId(), defIds);
		}
		try {
			HashMap<String, Object> resp = new HashMap<>();
			resp.put("user", user);
			resp.put("token", JwtUtil.createJWT( String.valueOf(user.getId()), Const.JWT_TTL));
			return ApiResultUtil.success(resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }

    @GetMapping(value = "/api/v1/logout")
    @ApiOperation(value = "退出")
    public Object logout() {
        SecurityUtils.getSubject().logout();
        return null;
    }

	@GetMapping(value = "/error")
	public Object error() {
		return null;
	}

}
